package org.jeecg.runner;

import com.baomidou.mybatisplus.core.toolkit.StringPool;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.constant.CacheConstant;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.Set;

@Slf4j
@Component
public class CacheUpdateRunner implements CommandLineRunner {

    /**
     * 系统启动时需要清除的 redis key 前缀
     */
    private static final String[] TO_BE_DELETE_REDIS_KEYS = new String[]{
            CacheConstant.SHOPPING_CART_LIST/*,
            CacheConstant.GOODS_ATTR_INFO,
            CacheConstant.GOODS_ATTR_LIST_BY_GOODS_ID,
            CacheConstant.GOODS_SPEC_INFO,
            CacheConstant.GOODS_SPEC_LIST_BY_GOODS_ID,
            CacheConstant.GOODS_CATEGORIES_INFO,
            CacheConstant.GOODS_CATEGORIES_LIST_BY_SHOP_ID*/
    };

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public void run(String... args) throws Exception {
        log.info("init redis data");

        RedisConnectionFactory connectionFactory = redisTemplate.getConnectionFactory();
        Assert.notNull(connectionFactory, "ConnectionFactory must not be null!");
        RedisConnection connection = connectionFactory.getConnection();
        for (String key : TO_BE_DELETE_REDIS_KEYS) {
            Set<byte[]> caches = connection.keys((key + StringPool.ASTERISK).getBytes());
            if (caches != null && !caches.isEmpty()) {
                connection.del(caches.toArray(new byte[][]{}));
            }
        }
        connection.close();
    }

}
